package Sever端;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import static java.lang.Thread.sleep;

public class SeverMain extends JFrame {
    SocketSever socketSever = new SocketSever();

    public SeverMain() {
        setSize(400, 200);
        setLocationRelativeTo(null);
        setTitle("简易聊天室服务端");
        setLayout(null);
        JButton[] btn = new JButton[3];
        String[] name = {"开启服务端", "停止服务端", "关闭客户端"};
        socketSever.start();
        int width = 100;
        int height = 40;
        int top_margin = (200 - height - 30) / 2;
        int gap = (400 - width * 3) / 4;
        for (int i = 0; i < 3; i++) {
            btn[i] = new JButton(name[i]);
            btn[i].setBounds((width + gap) * i + gap, top_margin, width, height);
            add(btn[i]);
        }
        btn[0].addMouseListener(//开启服务端
                new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        super.mouseClicked(e);
                        socketSever.Wake();
                    }
                }
        );
        btn[1].addMouseListener(//停止服务端
                new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        super.mouseClicked(e);
                        socketSever.Interrupt();
                    }
                }
        );
        btn[2].addMouseListener(//关闭客户端
                new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        super.mouseClicked(e);
                        socketSever.Stop();
                        try {
                            sleep(1000);
                        } catch (InterruptedException ex) {
                            throw new RuntimeException(ex);
                        }
                        System.exit(0);
                    }
                }
        );
        setVisible(true);
    }

    public static void main(String[] args) {
        new SeverMain();
    }
}